<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>整合jsonp、get、post请求的ajax封装</title>
</head>
<body>
    <script>
        // url封装
        function formate(url,dataObj){
            var start = true;
            var type = "GET";
            if(typeof url === 'object' && !(url instanceof Array)){
                dataObj = url;
                url = '';
                type = "POST";
            }

            // 2.参数拼接
            for(var key in dataObj){
                // get请求
                if(type === "GET"){
                    url += (start?"?":"&")+key+"="+dataObj[key];
                // post请求
                }else{
                    url += (start?"":"&")+key+"="+dataObj[key];
                }
                start = false;
            }
            return url;
        }

        // jsonp的ajax封装
        function ajax(method,url,_callback,dataObj){
            // 1.请求方式为jsonp时
            if(method === "jsonp"){
                // dataObj为空时，设置默认值
                dataObj = dataObj || {};
                
                dataObj.jsonpcallback = dataObj.jsonpcallback ? dataObj.jsonpcallback : "callback";

                var script = document.createElement("script");
                script.src = formate(url,dataObj);
                document.body.appendChild(script);

                window[dataObj.jsonpcallback] = data =>{
                    _callback(data);
                }

                script.remove();
            }
            // 2.请求方式为get/post时
            else{
                var xhr = new XMLHttpRequest();

                xhr.open(method,method.toUpperCase() ==="GET" ? formate(url,dataObj) : url);

                if(method.toUpperCase()==="POST"){
                    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
                }

                xhr.send(method.toUpperCase() ==="POST" ? formate(dataObj) : '');

                xhr.onreadystatechange = () =>{
                    if(xhr.readyState===4&&/^2\d{2}$/.test(xhr.status)){
                        _callback(xhr.responseText);
                    }
                }
            }
        }

        /* // get
        ajax("GET",'04_ajax_first.php',function(data){
            console.log(data);
        }) */

        // jsonp
        ajax("jsonp","https://api.gogoup.com/p1/data/recommend",function(data){
            console.log(data);
        });
    </script>
</body>
</html>